﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using CQIE.TES.IService;
using CQIE.TES.Model;
using CQIE.TES.WEB.USER.Models;

namespace CQIE.TES.WEB.USER.Controllers
{
    public class LoginController : Controller
    {
        public ITeacherService TeacherService { get; set; }
        public IStudentService StudentService { get; set; }

        // GET: Login
        public ActionResult Index()
        {
            if (TempData["error"]!=null)
            {
                ViewBag.error = "用户名或密码错误";
            }
            return View();
        }

        

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string username, string password)
        {
            bool isTeacher = Regex.IsMatch(username, @"^[0]{1}\d*$");
            Session.Clear();
            if (isTeacher)
            {
                Teacher teacher = TeacherService.Login(username, password);
                if (teacher==null)
                {
                    TempData["error"] = 1;
                    ViewBag.error = "用户名或密码错误";
                    return View("Index");
                }
                else
                {
                    Session["UID"] = teacher.ID;
                    return RedirectToAction("TeacherEvaIndex", "Evaluating", new RouteValueDictionary() { { "tid", teacher.ID } });
                }
            }
            else
            {
                // 学生登录
                Student student = StudentService.Login(username, password);
                if (student == null)
                {
                    
                    TempData["error"] = 1;
                    ViewBag.error = "用户名或密码错误";
                    return View("Index");
                }
                else
                {
                    Session["UID"] = student.ID;
                    return RedirectToAction("StudentEvaIndex", "Evaluating",new RouteValueDictionary(){{"sid",student.ID}});
                }

            }


        }
    }
}